package com.andrewchatham.pony;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.andrewchatham.SynctasticProto.AnnounceResponse;

public class Scan extends ListActivity implements Discoverer.Receiver {
  public static final String TAG = "Scan";
  public static final String RESPONSE_KEY = "response";
  private ArrayList<AnnounceResponse> mServers;

  class ServerListAdapter extends ArrayAdapter<AnnounceResponse> {
    public ServerListAdapter(Context context, ArrayList<AnnounceResponse> servers) {
      super(context, android.R.layout.simple_list_item_1, servers);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      TextView view = (TextView) super.getView(position, convertView, parent);
      AnnounceResponse r = getItem(position);
      view.setText(String.format("%s %s:%d", r.getHostname(), r.getAddress(), r.getPort()));
      return view;
    }
}

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scan);
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifi.getConnectionInfo().getBSSID() == null) {
      Toast.makeText(this, getString(R.string.connect_to_wifi), Toast.LENGTH_SHORT).show();
      finish();
    } else {
      new Discoverer(wifi, this).start();
    }
  }

  public void addAnnouncedServers(final ArrayList<AnnounceResponse> servers) {
    runOnUiThread(new Runnable() {
      public void run() {
        fillServerList(servers);
      }
    });
  }

  private void fillServerList(ArrayList<AnnounceResponse> servers) {
    if (servers == null) {
      Toast.makeText(this, getText(R.string.none_found), Toast.LENGTH_SHORT)
          .show();
      setResult(RESULT_CANCELED);
      finish();
      return;
    }
    mServers = servers;
    Log.d(TAG, "Adding servers " + servers.size());
    setListAdapter(new ServerListAdapter(this, servers));
  }

  protected void onListItemClick(ListView l, View v, int position, long id) {
    AnnounceResponse server = mServers.get(position);
    Intent response = new Intent();
    // Send the protocol buffer as the contents. 
    response.putExtra(RESPONSE_KEY, server.toByteArray());
    setResult(RESULT_OK, response); 
    finish();
  }
  
  public boolean onKeyDown(int keyCode, KeyEvent event) {
	  boolean returnValue = super.onKeyDown(keyCode, event);

	  if (keyCode == KeyEvent.KEYCODE_BACK)
		  setResult(RESULT_CANCELED);
	  return returnValue;
  }
}